package com.uetoken.cn.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.MsgBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.view.DialogHelper;
import com.uetoken.cn.view.keyboard.OnPasswordInputFinish;
import com.uetoken.cn.view.keyboard.PopEnterPassword;
import com.xuelianx.fingerlib.FingerFragment;
import com.xuelianx.fingerlib.FingerVerificationDialog;
import com.xuelianx.fingerlib.OnFingerprintFail;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 谢杨
 * @date 2018年7月24日15:54:08
 * 账号与安全
 */
public class AccountAndSafeActivity extends BaseActivity implements OnPasswordInputFinish, WebResponse, Handler.Callback, CompoundButton.OnCheckedChangeListener, PopupWindow.OnDismissListener {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_activity_account_and_safe_modify_account)
    TextView mTvAccount;
    @BindView(R.id.rl_activity_account_and_safe_modify_pw)
    RelativeLayout mRlModifyPw;
    @BindView(R.id.rl_activity_account_and_safe_modify_login_pwd)
    RelativeLayout mRlModifyLoginPwd;
    @BindView(R.id.rl_activity_account_and_safe_secret_payment)
    RelativeLayout mRlSecretPayment;
    @BindView(R.id.rl_activity_bind_account)
    RelativeLayout rlActivityBindAccount;
    @BindView(R.id.fingerprintPaymentSwitch)
    Switch fingerprintPaymentSwitch;

    /**
     * 请求登录接口的请求码
     */
    private static final int REQUEST_NETWORK_OPEN_FINGERPRINT = 10;
    /**
     * 请求签到接口的请求码
     */
    private static final int REQUEST_NETWORK_CLOSE_FINGERPRINT = 20;
    /**
     * 更新指纹开关按键状态
     */
    private static final int REQUEST_UPDATE_SWITCH = 30;
    private Dialog mOpenFingerprintPaymentDialog;
    private Dialog mFingerprintVerificationDialog;
    private FingerVerificationDialog fingerVerificationDialog;
    private String nodeid;
    private boolean isOpenStatus = false;//指纹
    private boolean isUpdateSwitch = true;
    private String notpwdpaytype;
    private PopEnterPassword popEnterPassword;
    private Handler mHandler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_account_and_safe;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);
        mHandler = new Handler(this);
        mTvTitle.setText(getString(R.string.str_safe_center));
        mIvBack.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        notpwdpaytype = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NOT_PWD_PAY_TYPE, "");
        nodeid = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_ID, "");
        String nodeCode = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_CODE, "");
        mTvAccount.setText(nodeCode);
        if (notpwdpaytype.contains("1")) {
            isOpenStatus = true;
        } else {
            isOpenStatus = false;
        }
        fingerprintPaymentSwitch.setChecked(isOpenStatus);
        fingerprintPaymentSwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void init() {

    }

    private void showOpenFingerprintPaymentDialog() {
        if (mOpenFingerprintPaymentDialog == null) {
            mOpenFingerprintPaymentDialog = DialogHelper.showOpenFingerprintPaymentDialog(AccountAndSafeActivity.this, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closeOpenFingerprintPaymentDialog();
                    showFingerprintVerificationDialog();
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closeOpenFingerprintPaymentDialog();
                    isOpenStatus = false;
                    mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
                }
            });
        } else {
            if (!mOpenFingerprintPaymentDialog.isShowing()) {
                mOpenFingerprintPaymentDialog.show();
            }
        }
    }

    private void showFingerprintVerificationDialog() {
        fingerVerificationDialog = new FingerVerificationDialog();
        fingerVerificationDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isOpenStatus = false;
                mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
                closeFingerprintVerificationDialog();
            }
        });
        fingerVerificationDialog.setOnFingerprintFail(new OnFingerprintFail() {
            @Override
            public void onFailed(String msg) {
                isOpenStatus = false;
                mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
                closeFingerprintVerificationDialog();
                showDialog("", getResources().getString(R.string.str_not_fingerprint), getResources().getString(R.string.str_cancel)
                        , getResources().getString(R.string.str_confirm), 1);
            }

            @Override
            public void onDeviceNotSupport() {
                isOpenStatus = false;
                mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
                closeFingerprintVerificationDialog();
                showDialog("", getResources().getString(R.string.str_device_nonsupport), getResources().getString(R.string.str_cancel)
                        , getResources().getString(R.string.str_confirm), 2);
            }
        });
        fingerVerificationDialog.show(getFragmentManager(), "fingerVerificationDialog");
        fingerVerificationDialog.setmFragmentCallBack(new FingerVerificationDialog.Callback() {
            @Override
            public void onSuccess() {
                isUpdateSwitch = false;
                closeFingerprintVerificationDialog();
                showEnterPasswordVerificationDialog();
            }

            @Override
            public void onFinish() {
                if (isUpdateSwitch) {
                    isOpenStatus = false;
                    mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
                } else {
                    isUpdateSwitch = true;
                }
            }

            @Override
            public void onError(int type) {
                if (type == 2) {
                    ToastUtils.showShort(R.string.str_fingerprint_verification_often);
                } else {
                    ToastUtils.showShort(R.string.str_fingerprint_verification_failed);
                }
                closeFingerprintVerificationDialog();
                closeOpenFingerprintPaymentDialog();
            }
        });
    }

    /**
     * @param type 1 指纹没有录入；2 设备不支持；3 关闭指纹支付
     */
    private void showDialog(String title, String message, String negativeStr, String positiveStr, final int type) {
        closeOpenFingerprintPaymentDialog();
        DialogHelper.showMessageDialog(AccountAndSafeActivity.this, title, message, negativeStr, positiveStr, new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        }, new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                if (type == 3) {
                    CloseFingerprintPayment();
                }
                dialog.dismiss();
            }
        });
    }

    private void showEnterPasswordVerificationDialog() {
        if (popEnterPassword == null) {
            popEnterPassword = new PopEnterPassword(AccountAndSafeActivity.this);
            popEnterPassword.setOnFinishInput(this);
            popEnterPassword.setOnDismissListener(this);
        }
        popEnterPassword.showAtLocation(this.findViewById(R.id.layoutContent),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
    }

    @OnClick({R.id.iv_back, R.id.rl_activity_account_and_safe_modify_pw, R.id.rl_activity_account_and_safe_modify_login_pwd, R.id.rl_activity_account_and_safe_secret_payment, R.id.rl_activity_bind_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_activity_account_and_safe_modify_pw:
                Intent intent = new Intent(this, ForgetPasswordActivity.class);
                intent.putExtra("pwd", "pay");
                startActivity(intent);
                break;
            case R.id.rl_activity_account_and_safe_modify_login_pwd:
                Intent modifyLoginIntent = new Intent(this, ForgetPasswordActivity.class);
                modifyLoginIntent.putExtra("pwd", "login");
                modifyLoginIntent.putExtra("modify", "modifylogin");
                startActivity(modifyLoginIntent);
                break;
            case R.id.rl_activity_account_and_safe_secret_payment:
                startActivity(new Intent(this, SecretPaymentActivity.class));
                break;
            case R.id.rl_activity_bind_account:
                startActivity(new Intent(this, BindAccountSettingActivity.class));
                break;
        }
    }

    /**
     * 开通指纹支付
     */
    private void OpenFingerprintPayment(String paypwd) {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getOpenFingerprintPaymentUrl(),
                REQUEST_NETWORK_OPEN_FINGERPRINT, Params.getOpenFingerprintPaymentParams(nodeid, EncodeUtils.base64Encode2String(paypwd.getBytes()), "1"));
    }

    /**
     * 关闭指纹支付
     */
    private void CloseFingerprintPayment() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getCloseFingerprintPaymentUrl(),
                REQUEST_NETWORK_CLOSE_FINGERPRINT, Params.getCloseFingerprintPaymentParams(nodeid, "1"));
    }

    @Override
    public void inputFinish(String password) {
        isUpdateSwitch = false;
        closeEnterPasswordVerificationDialog();
        OpenFingerprintPayment(password);
    }

    @Override
    public void cancelPwdKeyBoard() {
        isUpdateSwitch = true;
        if (popEnterPassword != null) {
            popEnterPassword.dismiss();
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("AccountAndSafeActivity== onSuccessResponse", "AccountAndSafeActivity== onSuccessResponse requestCode = " + requestCode + " response = " + response);
        dissmissDialog();
        switch (requestCode) {
            case REQUEST_NETWORK_OPEN_FINGERPRINT:
                MsgBean openMsgBean = new Gson().fromJson(response, MsgBean.class);
                if (openMsgBean.getResult() > 0) {
                    isOpenStatus = true;
                } else {
                    isOpenStatus = false;
                }
                mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
                ToastUtils.showShort(openMsgBean.getMessage());
                break;
            case REQUEST_NETWORK_CLOSE_FINGERPRINT:
                MsgBean closeMsgBean = new Gson().fromJson(response, MsgBean.class);
                if (closeMsgBean.getResult() > 0) {
                    isOpenStatus = false;
                } else {
                    isOpenStatus = true;
                }
                mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
                ToastUtils.showShort(closeMsgBean.getMessage());
                break;
        }

    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
        LogUtils.dTag("AccountAndSafeActivity== onFailResponse",
                "AccountAndSafeActivity== onFailResponse requestCode = " + requestCode + " e = " + e.toString());
    }

    private void closeOpenFingerprintPaymentDialog() {
        if (mOpenFingerprintPaymentDialog != null) {
            if (mOpenFingerprintPaymentDialog.isShowing()) {
                mOpenFingerprintPaymentDialog.dismiss();
            }
        }
    }

    private void closeFingerprintVerificationDialog() {
        if (fingerVerificationDialog != null && fingerVerificationDialog.getDialog() != null
                && fingerVerificationDialog.getDialog().isShowing()) {
            //dialog is showing so do something
            fingerVerificationDialog.dismiss();
            fingerVerificationDialog = null;
        }
    }

    private void closeEnterPasswordVerificationDialog() {
        if (popEnterPassword != null) {
            if (popEnterPassword.isShowing()) {
                popEnterPassword.dismiss();
            }
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case REQUEST_UPDATE_SWITCH:
                fingerprintPaymentSwitch.setOnCheckedChangeListener(null);
                fingerprintPaymentSwitch.setChecked(isOpenStatus);
                fingerprintPaymentSwitch.setOnCheckedChangeListener(this);
                break;
        }
        return false;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            showOpenFingerprintPaymentDialog();
        } else {
            showDialog("", getResources().getString(R.string.str_close_fingerprint_payment), getResources().getString(R.string.str_cancel)
                    , getResources().getString(R.string.str_confirm), 3);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            isUpdateSwitch = true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDismiss() {
        if (popEnterPassword != null) {
            popEnterPassword.setEmptyPassword();
        }
        if (isUpdateSwitch) {
            isUpdateSwitch = true;
            isOpenStatus = false;
            mHandler.sendEmptyMessage(REQUEST_UPDATE_SWITCH);
        }
    }
}
